package com.jwsoft.manager.core.dao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.module.base.common.util.CommonSecureUtil;
import com.jwsoft.manager.common.enums.EduStatusTypeEnum;
import com.jwsoft.manager.common.vo.eduDataTaskDetail.DataTaskDetailOptionVO;
import com.jwsoft.manager.core.dao.mapper.EduhSocialSecurityDetailMapper;
import com.jwsoft.manager.core.dao.mapper.EdutSocialSecurityDetailMapper;
import com.jwsoft.manager.core.dao.model.*;
import com.jwsoft.manager.core.dao.mapper.EduSocialSecurityDetailMapper;
import com.jwsoft.manager.core.dao.service.EduDataTaskDetailService;
import com.jwsoft.manager.core.dao.service.EduSocialSecurityDetailService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jwsoft.manager.core.dao.service.TableService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 服务实现类
 *
 * @author chenzh
 * @since 2023-03-21
 */
@Service
@Slf4j
public class EduSocialSecurityDetailServiceImpl extends ServiceImpl<EduSocialSecurityDetailMapper, EduSocialSecurityDetail> implements EduSocialSecurityDetailService, TableService {

    @Autowired
    private EduDataTaskDetailService detailService;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private EduhSocialSecurityDetailMapper hSocialSecurityDetailMapper;

    @Autowired
    private EdutSocialSecurityDetailMapper tSocialSecurityDetailMapper;

    private static final String SOCIAL_SECURITY_TABLE = "edu_social_security";
    //每次处理的数量为1w条数据
    private static final Integer PAGE_SIZE = 10000;

    @Override
    public Integer dataMigration(DataTaskDetailOptionVO optionVO) {
        EduDataTaskDetail taskDetail = detailService.getById(optionVO.getTaskDetailId());
        log.info("调用了EduSocialSecurityDetailServiceImpll服务的dataMigration()来进行处理迁移数据");
        Integer count = this.baseMapper.selectCountByYear(optionVO.getYear());
        log.info("edu_social_security_detail迁移" + count + "条数据");
        int totalPages = (count % PAGE_SIZE == 0) ? (count / PAGE_SIZE) : (count / PAGE_SIZE + 1);
        // 计算循环次数 = 总页数
        for (int i = 0; i < totalPages; i++) {
            List<EduSocialSecurityDetail> socialSecurityDetailList =
                    this.baseMapper.selectByYear(optionVO.getYear(),PAGE_SIZE);
            if (socialSecurityDetailList.size() > 0) {
                List<EduhSocialSecurityDetail> securityDetails = socialSecurityDetailList.stream().map(item -> {
                    EduhSocialSecurityDetail eduhSocialSecurityDetail = new EduhSocialSecurityDetail();
                    BeanUtils.copyProperties(item, eduhSocialSecurityDetail);
                    eduhSocialSecurityDetail.setTaskDetailId(taskDetail.getTaskDetailId());
                    //数据是否已加密，初始状态未加密
                    eduhSocialSecurityDetail.setEncryptFlag(BoolEnum.FALSE.getType());
                    eduhSocialSecurityDetail.setEncryptStatus(EduStatusTypeEnum.dcl.getType());
                    eduhSocialSecurityDetail.setCleanFlag(BoolEnum.FALSE.getType());
                    return eduhSocialSecurityDetail;
                }).collect(Collectors.toList());
                try {
                    this.performDataMigration(securityDetails, socialSecurityDetailList.size(), optionVO);
                } catch (Exception e) {
                    log.error("edu_social_security_detail迁移数据发生异常");
                    throw new RuntimeException("EduSocialSecurityDetailServiceImpl:" + e);
                }
            }
        }

        return count;
    }

    private void performDataMigration(List<EduhSocialSecurityDetail> securityDetails, Integer count, DataTaskDetailOptionVO optionVO) {
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                try {
                    //1.数据迁移到历史表
                    int saveHCount = hSocialSecurityDetailMapper.saveBatch(securityDetails);
                    if (saveHCount != count) {
                        throw new RuntimeException("数据迁移到历史表失败");
                    }
                    //2.数据销毁
                    EduDataTaskDetail taskDetail = detailService.getById(optionVO.getTaskDetailId());
                    if (ObjectUtils.isEmpty(taskDetail)) {
                        throw new AppException("任务数据不存在，请检查数据是否有误");
                    }
                    Integer deleteCount = baseMapper.deleteByTaskHistory(taskDetail.getTaskDetailId());
                    if (!count.equals(deleteCount)) {
                        throw new RuntimeException("数据删除失败");
                    }
                    log.info("edu_social_security_detail数据销毁成功！销毁数量：" + count);
                } catch (Exception e) {
                    status.setRollbackOnly();
                    throw e;
                }
            }
        });
    }

    @Override
    public void dataEncryption(DataTaskDetailOptionVO optionVO) {
        EduDataTaskDetail taskDetail = detailService.getById(optionVO.getTaskDetailId());
        log.info("调用了EduSocialSecurityDetailServiceImpl服务的dataEncryption()来进行处理数据加密");
        Integer count = 0;
        if (taskDetail.getEncryptCount() == 0) {
            count = this.baseMapper.selectEncryptionCountByYear(optionVO.getYear(), optionVO.getTaskDetailId());
            taskDetail.setEncryptCount(count);
        }
        Boolean errorFlag = false;
        Integer errorCount = 0;
        // 计算总页数
        int totalPages = (count % PAGE_SIZE == 0) ? (count / PAGE_SIZE) : (count / PAGE_SIZE + 1);
        // 计算循环次数 = 总页数
        for (int i = 0; i < totalPages; i++) {
            List<EduhSocialSecurityDetail> eduSocialSecurityDetails =
                    this.baseMapper.selectEncryptionByYear(optionVO.getYear(), optionVO.getTaskDetailId(),PAGE_SIZE);
            for (EduhSocialSecurityDetail hSocialSecurityDetail : eduSocialSecurityDetails) {
                try {
                    this.encrypt(hSocialSecurityDetail);
                    hSocialSecurityDetail.setEncryptTime(new Date());
                    hSocialSecurityDetail.setEncryptStatus(EduStatusTypeEnum.success.getType());
                    hSocialSecurityDetail.setEncryptRemarks("加密成功");
                    hSocialSecurityDetail.setEncryptFlag(BoolEnum.TRUE.getType());
                    hSocialSecurityDetailMapper.updateById(hSocialSecurityDetail);
                } catch (Exception e) {
                    //解密
                    this.decrypt(hSocialSecurityDetail);
                    hSocialSecurityDetail.setEncryptTime(new Date());
                    hSocialSecurityDetail.setEncryptStatus(EduStatusTypeEnum.error.getType());
                    hSocialSecurityDetail.setEncryptFlag(BoolEnum.FALSE.getType());
                    hSocialSecurityDetail.setEncryptRemarks("加密失败" + e.getMessage());
                    hSocialSecurityDetailMapper.updateById(hSocialSecurityDetail);
                    errorFlag = true;
                    errorCount++;
                    throw new AppException(e);
                }
            }
        }
        if (!errorFlag) {
            //无异常，返回任务状态
            taskDetail.setEncryptStatus(EduStatusTypeEnum.success.getType());
            taskDetail.setEncryptRemarks("加密成功");
            taskDetail.setEncryptTime(new Date());
        } else {
            taskDetail.setEncryptStatus(EduStatusTypeEnum.error.getType());
            taskDetail.setEncryptTime(new Date());
            taskDetail.setEncryptRemarks(taskDetail.getHandleTable()
                    +"加密失败,加密出错的数据：" + errorCount);
        }
        detailService.updateById(taskDetail);
    }

    private void decrypt(EduhSocialSecurityDetail hSocialSecurityDetail) {
        if (StringUtils.isNotBlank(hSocialSecurityDetail.getAac003())) {
            hSocialSecurityDetail.setAac003(CommonSecureUtil.sm4Decrypt(hSocialSecurityDetail.getAac003()));
        }
        if (StringUtils.isNotBlank(hSocialSecurityDetail.getAac147())) {
            hSocialSecurityDetail.setAac147(CommonSecureUtil.sm4Decrypt(hSocialSecurityDetail.getAac147()));
        }
    }

    private void encrypt(EduhSocialSecurityDetail hSocialSecurityDetail) {
        if (StringUtils.isNotBlank(hSocialSecurityDetail.getAac003())) {
            hSocialSecurityDetail.setAac003(CommonSecureUtil.sm4Encrypt(hSocialSecurityDetail.getAac003()));
        }
        if (StringUtils.isNotBlank(hSocialSecurityDetail.getAac147())) {
            hSocialSecurityDetail.setAac147(CommonSecureUtil.sm4Encrypt(hSocialSecurityDetail.getAac147()));
        }
    }

    @Override
    public Integer dataDestruction(DataTaskDetailOptionVO optionVO) {
        EduDataTaskDetail taskDetail = detailService.getById(optionVO.getTaskDetailId());
        log.info("调用了EduSocialSecurityDetailServiceImpl服务的dataDestruction来进行处理数据清洗");
        Boolean cleanFlag =
                detailService.verifyDestructionByTable(taskDetail.getYear(),SOCIAL_SECURITY_TABLE,taskDetail.getTaskId());
        if (!cleanFlag){
            //主表还未执行数据清洗，
            throw new AppException(SOCIAL_SECURITY_TABLE+"表还未执行完数据清洗，"+taskDetail.getHandleTable()+"无法进行清洗");
        }
        //查询副表中要清洗的数据
        List<EduhSocialSecurityDetail> hSocialSecurityDetails
                =this.baseMapper.queryCleanData(taskDetail.getTaskDetailId(),taskDetail.getYear());
        Integer cleanCount = hSocialSecurityDetails.size();
        if (cleanCount != 0){
            try {
                int batchSize = 1000;
                for (int i = 0; i<hSocialSecurityDetails.size(); i+= batchSize){
                    int endIndex = Math.min(i + batchSize, hSocialSecurityDetails.size());
                    List<EduhSocialSecurityDetail> eduhSocialSecurityDetails = hSocialSecurityDetails.subList(i, endIndex);
                    this.preformDataClean(eduhSocialSecurityDetails);
                }
            } catch (Exception e) {
                log.error("eduh_social_security_detail数据清洗发生异常");
                throw new RuntimeException("EduSocialSecurityDetailServiceImpl:" + e);
            }

        }
        return cleanCount;
    }

    private void preformDataClean(List<EduhSocialSecurityDetail> eduhSocialSecurityDetails) {
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                try {
                    List<EdutSocialSecurityDetail> tSocialSecurityDetails = eduhSocialSecurityDetails.stream().map(item -> {
                        EdutSocialSecurityDetail tSocialSecurityDetail = new EdutSocialSecurityDetail();
                        BeanUtils.copyProperties(item, tSocialSecurityDetail);
                        tSocialSecurityDetail.setCleanFlag(BoolEnum.TRUE.getType());
                        return tSocialSecurityDetail;
                    }).collect(Collectors.toList());
                    tSocialSecurityDetailMapper.saveBatch(tSocialSecurityDetails);
                    for (EduhSocialSecurityDetail eduhSocialSecurityDetail : eduhSocialSecurityDetails) {
                        hSocialSecurityDetailMapper.deleteHistoryById(eduhSocialSecurityDetail.getAaz223());
                    }
                } catch (Exception e) {
                    status.setRollbackOnly();
                    throw e;
                }
            }
        });
    }

    @Override
    public void tempDataDestruction() {
        System.out.println("空闲数据销毁");
    }

    @Override
    public void dataDecrypt(DataTaskDetailOptionVO optionVO) {
        Integer count = Math.toIntExact(hSocialSecurityDetailMapper.selectCount(new QueryWrapper<EduhSocialSecurityDetail>().lambda()
                .eq(EduhSocialSecurityDetail::getTaskDetailId, optionVO.getTaskDetailId())));
        int totalPages = (count % PAGE_SIZE == 0) ? (count / PAGE_SIZE) : (count / PAGE_SIZE + 1);
        int currentPage = 0;
        for (int i = 0; i < totalPages; i++) {
            List<EduhSocialSecurityDetail> hSocialSecurityDetails =
                    hSocialSecurityDetailMapper.selectByTaskDetailId(optionVO.getTaskDetailId(),currentPage,PAGE_SIZE);
            List<EdutSocialSecurityDetail> tSocialSecurityDetails = hSocialSecurityDetails.stream().map(eduhSocialSecurityDetail -> {
                if (BoolEnum.TRUE.getType().equalsIgnoreCase(eduhSocialSecurityDetail.getEncryptFlag())) {
                    //需要进行解密
                    this.decrypt(eduhSocialSecurityDetail);
                }
                EdutSocialSecurityDetail socialSecurityDetail = new EdutSocialSecurityDetail();
                BeanUtils.copyProperties(eduhSocialSecurityDetail, socialSecurityDetail);
                return socialSecurityDetail;
            }).collect(Collectors.toList());
            tSocialSecurityDetailMapper.saveBatch(tSocialSecurityDetails);
            currentPage ++;
        }

    }
}
